/*!
 * admin.js
 *
 * Copyright 2016 Lajox
 */

//判断函数是否存在
var function_exists = function(funcName) {
    var isFunction = false;
    try{
        var isString = Object.prototype.toString.call(funcName) === "[object String]";
        if(isString) {
            isFunction = typeof(eval(funcName))=="function";
        }
        else {
            isFunction = typeof(funcName)=="function";
        }
    }catch(e){}
    return isFunction;
};

//读取cookie
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    };

    return null;
}

//设置cookie
function setCookie(name, value, days) {
    var argc = setCookie.arguments.length;
    var argv = setCookie.arguments;
    var secure = (argc > 5) ? argv[5] : false;
    var expire = new Date();
    if(days==null || days==0) days=1;
    expire.setTime(expire.getTime() + 3600000*24*days);
    document.cookie = name + "=" + escape(value) + ("; path=/") + ((secure == true) ? "; secure" : "") + ";expires="+expire.toGMTString();
}

window.MsgBox = (function($) {
    "use strict";

    var elem,
        hideHandler,
        that = {};
    var alertStyles=['alert-info','alert-success','alert-error','alert-warning','alert-danger'];

    that.init = function() {
        if(elem){
            return;
        }
        var html='<div id="message_box" class="alert alert-info alert-block" style="display:none;width:500px;position:fixed;'+
            'left:50%;margin-left:-250px;top:0px;z-index:10000;"><button type="button" class="close">&times;</button>'+
            '<span></span></div>';
        $("body").append(html);
        elem=$("#message_box");
        elem.find('button.close').click(function(){
            that.hide();
        });
    };

    that.show = function(text,type,time,fc,args) {
        type = type || 'info';
        if(elem==null ||elem==undefined){
            that.init();
        }
        var alertClass='alert-'+type;
        for ( var i = 0; i < alertStyles.length; i++) {
            elem.removeClass(alertStyles[i]);
        }
        if(alertClass!=''){
            elem.addClass(alertClass);
        }
        clearTimeout(hideHandler);
        elem.find("span").html(text);
        elem.slideDown('slow');
        if(time==null || isNaN(time)){
            time=3000;
        }
        hideHandler = setTimeout(function() {
            that.hide(fc,args);
        }, time);
    };

    that.info=function(text,time,fc,args){
        that.show(text,"info",time,fc,args);
    };

    that.error=function(text,time,fc,args){
        that.show(text,"error",time,fc,args);
    };

    that.warning=function(text,time,fc,args){
        that.show(text,"warning",time,fc,args);
    };

    that.success=function(text,time,fc,args){
        that.show(text,"success",time,fc,args);
    };

    that.hide = function(fc,args) {
        if(fc) {
            if(typeof fc != "function") {
                var fun = new Function('args','return '+fc+'(args)');
                fun(args);
            }
            else {
                if(args) {
                    fc.call(this,args);
                } else {
                    fc.call(this);
                }
            }
        }
        elem.fadeOut();
    };

    return that;
}(jQuery));

function ajaxDo(type, url, data, time, fa, fb) {
    type = type || 'GET';
    time = time || 3;
    $.ajax({
        url: url,
        data: data,
        type: type.toUpperCase(),
        cache: false,
        dataType: "json",
        success: function (e) {
            if (e.info) {
                if (e.status) {
                    MsgBox.success(e.info, time * 1000, fa, e);
                } else {
                    MsgBox.error(e.info, time * 1000, fb, e);
                }
            }
        }
    });
}

function ajaxGet(url, data, time, fa, fb) {
    ajaxDo('GET', url, data, time, fa, fb);
}

function ajaxPost(url, data, time, fa, fb) {
    ajaxDo('POST', url, data, time, fa, fb);
}

//Ajax载入表单
function ajaxForm(url, title) {
    title = title || '设置信息';
    BootstrapDialog.configDefaultOptions({nl2br:false});
    BootstrapDialog.show({
        title: title,
        message: function(dialog) {
            var dom = $('<div></div>').load(url);
            dialog.setClosable(true);
            return dom;
        },
        buttons: [{
            label: '取消',
            action: function(dialogItself){
                dialogItself.close();
            }
        }, {
            label: '提交',
            cssClass: 'btn-primary',
            action: function(dialog){
                dialog.getModalBody().find('form').submit();
            }
        }]
    });
}

function doItem(url, params, title, type) {
    params = params || {};
    title = title || '确定进行此操作吗?';
    type = type || 'POST';
    BootstrapDialog.confirm(title, function(result){
        if(result) {
            ajaxDo(type, url, params, 3, function (result) {
                if(result.url){
                    location.href = result.url;
                }else{
                    location.reload();
                }
            }, function() {
                MsgBox.error('操作失败');
            });
        }
    });
}

function delItem(url, params, type) {
    doItem(url, params, '确定删除吗?', type);
}

$(function() {
    //bootstrap popover
    $("[data-toggle='popover']").popover({ trigger: 'focus', html: true });

    //状态切换
    $(document).on('click','.res-status .icon',function(){
        var p = $(this).parents('.res-status'),
            url = p.attr('data-url') || '',
            id = p.attr('data-id') || '',
            _ok = p.attr('data-status-ok') || '正常',
            _no = p.attr('data-status-no') || '失败',
            status = $(this).is('.fa-check') ? 0 : 1;
        if(url && id) {
            $.ajax({
                url: url,
                data: {id: id, status : status},
                type: 'GET',
                cache: false,
                dataType: "text",
                success: function (r) {
                    if (r=='ok') {
                        if(status==1) {
                            p.html('<span data-toggle="tooltip" title="'+_ok+'"><i class="icon fa fa-check text-green"></i></span>');
                        }
                        else {
                            p.html('<span data-toggle="tooltip" title="'+_no+'"><i class="icon fa fa-close text-red"></i></span>');
                        }
                    } else {
                        //alert('系统出错');
                    }
                }
            });
        }
    });

    //隐藏面包屑导航
    //$('.breadcrumb').css('display','none');
});

$(function() {
    //全选、不选
    $('input[name="btSelectAll"]').click(function() {
        $('input[name="ids"]').prop('checked', this.checked);
    });
    $("input[name='ids']").click(function() {
        var $subs = $("input[name='ids']");
        $('input[name="btSelectAll"]').prop("checked" , $subs.length == $subs.filter(":checked").length ? true :false);
    });

    //删除
    $('.input-group button[name=delete]').click(function() {
        var chks =[];
        $("input[name='ids']").filter(":checked").each(function() {
            chks.push($(this).val());
        });
        var id = chks.join(',');
        if(!id) {
            //alert('请至少选择一项');
            MsgBox.error('请至少选择一项');
            return;
        }
        //存在指定函数
        var fun = $(this).attr('data-fun');
        if(fun && function_exists(fun)) {
            var fc = new Function('id','return '+fun+'(id)');
            fc(id);
        }
        //不存在指定函数时，需指定data-url属性，外加可选data-id属性
        else {
            var data = {}, url = $(this).attr('data-url');
            if(url) {
                var field = $(this).attr('data-id') ? $(this).attr('data-id') : 'id';
                data[field] = id;
                delItem(url, data);
            }
        }
    });

    //刷新
    $('.input-group button[name=refresh]').click(function() {
        location.reload();
    });

    //全部展开 折叠
    $('.input-group button[name=toggle]').click(function() {
        if($(this).attr('toggle-num')==1) {
            $("tr[id^='data-tr-']").hide();
            $(".row-details").addClass("fa-plus-square-o").removeClass("fa-minus-square-o");
            $(this).attr('toggle-num',0);
        }
        else {
            $("tr[id^='data-tr-']").show();
            $(".row-details").removeClass("fa-plus-square-o").addClass("fa-minus-square-o");
            $(this).attr('toggle-num',1);
        }
    });
});